import { cloudbaseApp, development } from '@/cloudbaseapi/cloudbase-api'
const db = cloudbaseApp().database()
const $ = db.command.aggregate
const _ = db.command
const { HDBDBNAME, JINWENGDB, HDINDEXIMG, SGBDBNAME } = development()

export async function getItems(limit, page, _id) {
  const where = { _id: parseInt(_id) }
  if(!_id) {
    delete where['_id']
  }
  const skip = (page - 1) * limit
  const count = await db.collection(HDBDBNAME).where(where).count()
  const total = count.total
  const data = await db.collection(HDBDBNAME).where(where).limit(limit).skip(skip).orderBy('_id','desc').get()
  data['total'] = total
  return data
}
export async function getItem(id) {
  console.log(id)
  return await db.collection(HDBDBNAME).doc(id).get()
}
export function getJwItems() {
  return db.collection(JINWENGDB).limit(1000).get()
}
export function getIndexImg() {
  return db.collection(HDINDEXIMG).limit(1000).get()
}
export function getJwItem(id) {
  return db.collection(JINWENGDB).doc(id).get()
}
export function getSrZmList() {
  return db.collection(SGBDBNAME).where({shijiIndex: 3 }).limit(1000).get()
}
export function getSrZmItemId(id) {
  return db.collection(SGBDBNAME).where({shijiIndex: 3, _id: id }).get()
}
export function update(data, type) {
  const id = parseInt(data._id)
  delete data['_id']
  delete data['_openid']
  return new Promise((resolve, reject) => {

    if(type == 'create') {
      db.collection(HDBDBNAME).doc(id).get().then(res => {
        const datar = res.data
        if(datar.length > 0) {
          reject(new Error('当前ID已经有数据了'))
        } else {
          db.collection(HDBDBNAME).doc(id).set(data).then(res=>{
            resolve(res)
          }).catch(err => {
            reject(err)
          })
        }
      })
    } else if(type == 'edit') {
      db.collection(HDBDBNAME).doc(id).set(data).then(res=>{
        resolve(res)
      }).catch(err => {
        reject(err)
      })
    }
  })
}
// zhengle()
export async function zhengle() {
  const basuUrl = 'https://7367-sgb-8gqmg7kv48722f4e-1306391227.tcb.qcloud.la/hd/hddmt/'
  const hdListData = await db.collection(HDBDBNAME).limit(1000).get()
  const list = hdListData.data
  list.filter(item => {
    console.log(item)
    if(item.wrapper[0].imgUrl !== ''){
      item.wrapper[0].imgUrl = basuUrl + item.wrapper[0].imgUrl
    }
    if(item.wrapper[1].imgUrl !== ''){
      item.wrapper[1].imgUrl = basuUrl + item.wrapper[1].imgUrl
    }
    if(item.wrapper[0].audioUrl !==''){
      item.wrapper[0].audioUrl = basuUrl + item.wrapper[0].audioUrl
    }
    if(item.wrapper[1].audioUrl !== ''){
      item.wrapper[1].audioUrl = basuUrl + item.wrapper[1].audioUrl
    }
  })
  console.log(list)
}
